<template>
  <div class="charts" ref="root" style="height: 100%;width: 100%"></div>
</template>

<script>
import {defineComponent} from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  name: 'ArkChart',
  emit: ['instanced'],
  props: {
    initTheme: {
      type: [String, Object],
    },
    initOpts: {
      type: Object,
    },
    options: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      echartsInstance: {},
      resizeObserver: null,
    };
  },
  watch: {
    options: {
      deep: true,
      handler(newVal) {
        if (!newVal) return;

        this.echartsInstance.setOption(newVal);
      }
    },
  },
  mounted() {
    this.init();
  },
  beforeUnmount() {
    this.resizeObserver?.unobserve(this.$refs.root);
    this.echartsInstance?.dispose();
  },
  methods: {
    init() {
      const el = this.$refs.root;

      // 初始化ECharts
      let echartsInstance = echarts.init(el, this.initTheme, this.initOpts);

      // 设置ECharts配置项
      if (this.options) {
        echartsInstance.setOption(this.options);
      }

      // 监听容器大小变化
      if (!this.resizeObserver) {
        this.resizeObserver = new ResizeObserver((entries) => {
          window.requestAnimationFrame(() => {
            for (const entry of entries) {
              echartsInstance.resize();
            }
          });
        });
        this.resizeObserver.observe(el);
      }

      this.echartsInstance = echartsInstance;
      this.$emit('instanced', echartsInstance);
    },

    // 供外部调用，内部未使用
    getEChartsInstance() {
      return this.echartsInstance;
    },
  },
});
</script>